package cn.iocoder.yudao.module.reading.service.assignment;

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.reading.controller.app.assignment.vo.*;
import cn.iocoder.yudao.module.reading.dal.dataobject.assignment.*;
import cn.iocoder.yudao.module.reading.dal.dataobject.book.PictureBookDO;
import cn.iocoder.yudao.module.reading.dal.dataobject.bookset.BookSetDO;
import cn.iocoder.yudao.module.reading.dal.dataobject.classes.ClassDO;
import cn.iocoder.yudao.module.reading.dal.dataobject.classes.ClassMemberDO;
import cn.iocoder.yudao.module.reading.dal.dataobject.user.UserDO;
import cn.iocoder.yudao.module.reading.dal.mysql.assignment.*;
import cn.iocoder.yudao.module.reading.dal.mysql.book.PictureBookMapper;
import cn.iocoder.yudao.module.reading.dal.mysql.bookset.BookSetMapper;
import cn.iocoder.yudao.module.reading.dal.mysql.classes.ClassMemberMapper;
import cn.iocoder.yudao.module.reading.dal.mysql.user.UserMapper;
import cn.iocoder.yudao.module.reading.service.classes.ClassService;
import cn.iocoder.yudao.module.reading.service.user.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

import jakarta.annotation.Resource;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.reading.enums.ErrorCodeConstants.*;

/**
 * 班级作业管理 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class AssignmentServiceImpl implements AssignmentService {

    @Resource
    private ClassAssignmentMapper classAssignmentMapper;
    @Resource
    private AssignmentBookMapper assignmentBookMapper;
    @Resource
    private AssignmentCompletionMapper assignmentCompletionMapper;
    @Resource
    private AssignmentClassMapper assignmentClassMapper;
    @Resource
    private ClassMemberMapper classMemberMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private PictureBookMapper pictureBookMapper;
    @Resource
    private BookSetMapper bookSetMapper;
    @Resource
    private ClassService classService;
    @Resource
    private UserService userService;

    @Override
    public List<AssignmentRespVO> getClassAssignments(Long classId, Long userId) {
        // 检查班级是否存在
        classService.getClass(classId);

        // 检查用户是否为班级创建者或成员
        boolean isCreator = classService.isClassCreator(classId, userId);
        boolean isMember = classService.isClassMember(classId, userId);

        if (!isCreator && !isMember) {
            throw exception(CLASS_MEMBER_NOT_EXISTS);
        }

        // 查询班级作业（包括单班级作业和跨班级作业）
        List<ClassAssignmentDO> assignments = new ArrayList<>();

        // 1. 查询单班级作业
        List<ClassAssignmentDO> singleClassAssignments = classAssignmentMapper.selectByClassId(classId);
        assignments.addAll(singleClassAssignments);

        // 2. 查询跨班级作业
        List<Long> multiClassAssignmentIds = assignmentClassMapper.selectAssignmentIdsByClassId(classId);
        if (!multiClassAssignmentIds.isEmpty()) {
            List<ClassAssignmentDO> multiClassAssignments = classAssignmentMapper.selectBatchIds(multiClassAssignmentIds);
            assignments.addAll(multiClassAssignments);
        }

        if (assignments.isEmpty()) {
            return new ArrayList<>();
        }

        // 如果是学生，过滤出用户参与的作业
        if (!isCreator) {
            List<ClassAssignmentDO> userAssignments = new ArrayList<>();
            for (ClassAssignmentDO assignment : assignments) {
                // 检查用户是否参与了这个作业
                List<AssignmentCompletionDO> userCompletions = assignmentCompletionMapper
                        .selectByAssignmentIdAndUserId(assignment.getId(), userId);
                if (!userCompletions.isEmpty()) {
                    userAssignments.add(assignment);
                }
            }
            assignments = userAssignments;
        }

        // 转换为响应VO
        List<AssignmentRespVO> result = new ArrayList<>();
        for (ClassAssignmentDO assignment : assignments) {
            AssignmentRespVO respVO = BeanUtils.toBean(assignment, AssignmentRespVO.class);

            // 查询作业包含的绘本
            List<AssignmentBookDO> assignmentBooks = assignmentBookMapper.selectByAssignmentId(assignment.getId());
            if (!assignmentBooks.isEmpty()) {
                List<Long> bookIds = assignmentBooks.stream()
                        .map(AssignmentBookDO::getBookId)
                        .collect(Collectors.toList());
                List<PictureBookDO> books = pictureBookMapper.selectBatchIds(bookIds);

                Map<Long, PictureBookDO> bookMap = books.stream()
                        .collect(Collectors.toMap(PictureBookDO::getId, b -> b));

                List<AssignmentRespVO.AssignmentBookRespVO> bookVOs = new ArrayList<>();
                for (AssignmentBookDO assignmentBook : assignmentBooks) {
                    PictureBookDO book = bookMap.get(assignmentBook.getBookId());
                    if (book != null) {
                        AssignmentRespVO.AssignmentBookRespVO bookVO = new AssignmentRespVO.AssignmentBookRespVO();
                        bookVO.setId(book.getId());
                        bookVO.setTitle(book.getTitle());
                        bookVO.setCover(book.getCover());
                        bookVO.setSortOrder(assignmentBook.getSortOrder());
                        bookVOs.add(bookVO);
                    }
                }
                respVO.setBooks(bookVOs);
            }

            // 转换URL
            respVO.convertUrls();

            result.add(respVO);
        }

        return result;
    }

    @Override
    public AssignmentRespVO getAssignmentDetail(Long assignmentId, Long userId) {
        // 检查作业是否存在
        ClassAssignmentDO assignment = validateAssignmentExists(assignmentId);

        // 检查用户是否有权限查看作业
        boolean hasPermission = false;
        if (assignment.getCreatorId().equals(userId)) {
            // 用户是作业创建者，有权限查看
            hasPermission = true;
        } else if (assignment.getIsMultiClass() != null && assignment.getIsMultiClass()) {
            // 跨班级作业：检查用户是否为任一关联班级的成员
            List<Long> classIds = assignmentClassMapper.selectClassIdsByAssignmentId(assignmentId);
            for (Long classId : classIds) {
                if (classService.isClassMember(classId, userId)) {
                    hasPermission = true;
                    break;
                }
            }
        } else if (assignment.getClassId() != null) {
            // 单班级作业：检查用户是否为班级成员
            hasPermission = classService.isClassMember(assignment.getClassId(), userId);
        }

        if (!hasPermission) {
            throw exception(CLASS_MEMBER_NOT_EXISTS);
        }

        // 转换为响应VO
        AssignmentRespVO respVO = BeanUtils.toBean(assignment, AssignmentRespVO.class);

        // 查询作业包含的绘本
        List<AssignmentBookDO> assignmentBooks = assignmentBookMapper.selectByAssignmentId(assignmentId);
        if (!assignmentBooks.isEmpty()) {
            List<Long> bookIds = assignmentBooks.stream()
                    .map(AssignmentBookDO::getBookId)
                    .collect(Collectors.toList());
            List<PictureBookDO> books = pictureBookMapper.selectBatchIds(bookIds);

            Map<Long, PictureBookDO> bookMap = books.stream()
                    .collect(Collectors.toMap(PictureBookDO::getId, b -> b));

            List<AssignmentRespVO.AssignmentBookRespVO> bookVOs = new ArrayList<>();
            for (AssignmentBookDO assignmentBook : assignmentBooks) {
                PictureBookDO book = bookMap.get(assignmentBook.getBookId());
                if (book != null) {
                    AssignmentRespVO.AssignmentBookRespVO bookVO = new AssignmentRespVO.AssignmentBookRespVO();
                    bookVO.setId(book.getId());
                    bookVO.setTitle(book.getTitle());
                    bookVO.setCover(book.getCover());
                    bookVO.setSortOrder(assignmentBook.getSortOrder());
                    bookVO.setIsCompleted(assignmentBookMapper.selectIsCompletedByBookIdAndAssignmentIdAndUserId(book.getId(), assignmentId, userId));
                    bookVOs.add(bookVO);
                }
            }
            respVO.setBooks(bookVOs);
        }

        // 转换URL
        respVO.convertUrls();

        return respVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createAssignment(Long userId, AssignmentCreateReqVO createReqVO) {
        // 如果提供了多班级ID列表，使用多班级创建方法
        if (createReqVO.getClassIds() != null && createReqVO.getClassIds().size() > 1) {
            List<Long> assignmentIds = createMultiClassAssignment(userId, createReqVO);
            return assignmentIds.get(0); // 返回第一个作业ID
        }

        // 单班级创建逻辑
        Long classId = createReqVO.getClassId();
        if (createReqVO.getClassIds() != null && !createReqVO.getClassIds().isEmpty()) {
            classId = createReqVO.getClassIds().get(0); // 如果提供了classIds，使用第一个
            createReqVO.setClassId(classId); // 更新classId字段
        }

        // 检查班级是否存在
        classService.getClass(classId);

        // 检查用户是否为班级创建者
        if (!classService.isClassCreator(classId, userId)) {
            throw exception(CLASS_NO_PERMISSION);
        }

        // 获取班级所有成员
        List<ClassMemberDO> allMembers = classMemberMapper.selectByClassId(createReqVO.getClassId());

        List<ClassMemberDO> participatingMembers;

        // 如果指定了参与成员，则只使用指定的成员
        if (createReqVO.getParticipantMemberIds() != null && !createReqVO.getParticipantMemberIds().isEmpty()) {
            final List<Long> participantMemberIds = createReqVO.getParticipantMemberIds();
            participatingMembers = allMembers.stream()
                    .filter(member -> participantMemberIds.contains(member.getUserId()))
                    .collect(Collectors.toList());
        } else {
            // 否则使用排除逻辑（兼容旧版本）
            final List<Long> excludedMemberIds = createReqVO.getExcludedMemberIds() != null
                    ? createReqVO.getExcludedMemberIds()
                    : new ArrayList<>();

            participatingMembers = allMembers.stream()
                    .filter(member -> !excludedMemberIds.contains(member.getUserId()))
                    .collect(Collectors.toList());
        }

        Integer participatingMemberCount = participatingMembers.size();

        // 创建作业
        ClassAssignmentDO assignment = ClassAssignmentDO.builder()
                .classId(createReqVO.getClassId())
                .creatorId(userId)
                .title(createReqVO.getTitle())
                .assignmentDate(createReqVO.getAssignmentDate())
                .requirementType(createReqVO.getRequirementType())
                .description(createReqVO.getDescription())
                .totalBooks(createReqVO.getBookIds().size())
                .completedCount(0)
                .totalMembers(participatingMemberCount)
                .isMultiClass(false) // 单班级作业
                .isActive(true)
                .build();
        classAssignmentMapper.insert(assignment);

        // 创建作业绘本关联
        for (int i = 0; i < createReqVO.getBookIds().size(); i++) {
            AssignmentBookDO assignmentBook = AssignmentBookDO.builder()
                    .assignmentId(assignment.getId())
                    .bookId(createReqVO.getBookIds().get(i))
                    .sortOrder(i + 1)
                    .build();
            assignmentBookMapper.insert(assignmentBook);
        }

        // 为参与作业的成员创建完成记录
        for (ClassMemberDO member : participatingMembers) {
            for (Long bookId : createReqVO.getBookIds()) {
                AssignmentCompletionDO completion = AssignmentCompletionDO.builder()
                        .assignmentId(assignment.getId())
                        .userId(member.getUserId())
                        .bookId(bookId)
                        .completionType(createReqVO.getRequirementType())
                        .isCompleted(false)
                        .score(0)
                        .build();
                assignmentCompletionMapper.insert(completion);
            }
        }

        log.info("用户 {} 在班级 {} 创建作业成功，作业ID: {}，参与成员数: {}",
                userId, createReqVO.getClassId(), assignment.getId(), participatingMemberCount);
        return assignment.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Long> createMultiClassAssignment(Long userId, AssignmentCreateReqVO createReqVO) {
        // 验证多班级是否存在
        classService.validateMultiClassExists(createReqVO.getClassIds());

        // 检查用户是否为所有班级的创建者
        if (!classService.isMultiClassCreator(createReqVO.getClassIds(), userId)) {
            throw exception(CLASS_NO_PERMISSION, "用户不是所有班级的创建者");
        }

        // 收集所有班级的参与成员
        Set<Long> allParticipatingMemberIds = new HashSet<>();
        int totalMembersCount = 0;

        for (Long classId : createReqVO.getClassIds()) {
            // 获取班级成员
            List<ClassMemberDO> classMembers = classMemberMapper.selectByClassId(classId);

            // 如果指定了参与成员，则过滤；否则包含所有成员
            if (createReqVO.getParticipantMemberIds() != null && !createReqVO.getParticipantMemberIds().isEmpty()) {
                Set<Long> participantSet = new HashSet<>(createReqVO.getParticipantMemberIds());
                for (ClassMemberDO member : classMembers) {
                    if (participantSet.contains(member.getUserId())) {
                        allParticipatingMemberIds.add(member.getUserId());
                    }
                }
            } else {
                // 包含所有成员（排除老师）
                for (ClassMemberDO member : classMembers) {
                    if (!"teacher".equals(member.getRole())) {
                        allParticipatingMemberIds.add(member.getUserId());
                    }
                }
            }
            totalMembersCount += classMembers.size();
        }

        // 创建跨班级作业（class_id设为null，is_multi_class设为true）
        ClassAssignmentDO assignment = ClassAssignmentDO.builder()
                .classId(null) // 跨班级作业不关联单个班级
                .creatorId(userId)
                .title(createReqVO.getTitle())
                .assignmentDate(createReqVO.getAssignmentDate())
                .requirementType(createReqVO.getRequirementType())
                .description(createReqVO.getDescription())
                .totalBooks(createReqVO.getBookIds().size())
                .completedCount(0)
                .totalMembers(allParticipatingMemberIds.size())
                .isMultiClass(true)
                .isActive(true)
                .build();
        classAssignmentMapper.insert(assignment);

        // 创建作业-班级关联记录
        List<AssignmentClassDO> assignmentClasses = new ArrayList<>();
        for (Long classId : createReqVO.getClassIds()) {
            AssignmentClassDO assignmentClass = AssignmentClassDO.builder()
                    .assignmentId(assignment.getId())
                    .classId(classId)
                    .build();
            assignmentClasses.add(assignmentClass);
        }
        for (AssignmentClassDO assignmentClass : assignmentClasses) {
            assignmentClassMapper.insert(assignmentClass);
        }

        // 创建作业绘本关联
        for (int i = 0; i < createReqVO.getBookIds().size(); i++) {
            AssignmentBookDO assignmentBook = AssignmentBookDO.builder()
                    .assignmentId(assignment.getId())
                    .bookId(createReqVO.getBookIds().get(i))
                    .sortOrder(i + 1)
                    .build();
            assignmentBookMapper.insert(assignmentBook);
        }

        // 为所有参与成员创建完成记录（每个学生只需要完成一次）
        for (Long userId1 : allParticipatingMemberIds) {
            for (Long bookId : createReqVO.getBookIds()) {
                AssignmentCompletionDO completion = AssignmentCompletionDO.builder()
                        .assignmentId(assignment.getId())
                        .userId(userId1)
                        .bookId(bookId)
                        .completionType(createReqVO.getRequirementType())
                        .isCompleted(false)
                        .score(0)
                        .build();
                assignmentCompletionMapper.insert(completion);
            }
        }

        log.info("用户 {} 创建跨班级作业成功，作业ID: {}，涉及班级: {}，参与成员数: {}",
                userId, assignment.getId(), createReqVO.getClassIds(), allParticipatingMemberIds.size());

        // 返回单个作业ID的列表（保持接口兼容性）
        return Collections.singletonList(assignment.getId());
    }

    @Override
    public List<AssignmentRespVO> getMultiClassAssignments(Long userId, List<Long> classIds) {
        List<AssignmentRespVO> allAssignments = new ArrayList<>();

        for (Long classId : classIds) {
            // 检查用户是否为班级成员
            if (!classService.isClassMember(classId, userId)) {
                continue; // 跳过用户不是成员的班级
            }

            // 获取该班级的作业列表
            List<ClassAssignmentDO> assignments = classAssignmentMapper.selectByClassId(classId);

            for (ClassAssignmentDO assignment : assignments) {
                AssignmentRespVO respVO = BeanUtils.toBean(assignment, AssignmentRespVO.class);

                // 设置班级信息
                ClassDO classDO = classService.getClass(classId);
                if (classDO != null) {
                    // 注意：ClassDO 的字段名是 className，不是 name
                    // 由于 AssignmentRespVO 没有 setClassName 方法，我们暂时跳过这个设置
                    // respVO.setClassName(classDO.getClassName());
                }

                // 设置创建者信息
                // 注意：UserService 没有 getUser 方法，我们使用 userMapper 直接查询
                UserDO creator = userMapper.selectById(assignment.getCreatorId());
                if (creator != null) {
                    // 注意：AssignmentRespVO 没有 setCreatorName 方法，我们暂时跳过这个设置
                    // respVO.setCreatorName(creator.getNickname());
                }

                allAssignments.add(respVO);
            }
        }

        // 按创建时间倒序排列
        allAssignments.sort((a, b) -> b.getCreateTime().compareTo(a.getCreateTime()));

        return allAssignments;
    }

    /**
     * 验证作业是否存在
     */
    private ClassAssignmentDO validateAssignmentExists(Long assignmentId) {
        ClassAssignmentDO assignment = classAssignmentMapper.selectById(assignmentId);
        if (assignment == null) {
            throw exception(ASSIGNMENT_NOT_EXISTS);
        }
        return assignment;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAssignment(Long assignmentId, Long userId, AssignmentUpdateReqVO updateReqVO) {
        // 检查作业是否存在
        ClassAssignmentDO assignment = validateAssignmentExists(assignmentId);

        // 检查用户是否为作业创建者
        if (!assignment.getCreatorId().equals(userId)) {
            throw exception(ASSIGNMENT_NO_PERMISSION);
        }

        // 更新作业基本信息
        ClassAssignmentDO updateDO = ClassAssignmentDO.builder()
                .id(assignmentId)
                .title(updateReqVO.getTitle())
                .description(updateReqVO.getDescription())
                .requirementType(updateReqVO.getRequirementType())
                .assignmentDate(updateReqVO.getAssignmentDate())
                .build();

        // 如果提供了参与成员列表，则更新成员
        if (updateReqVO.getParticipantMemberIds() != null) {
            updateAssignmentMembers(assignmentId, assignment, updateReqVO.getParticipantMemberIds());
            // 更新总成员数
            updateDO.setTotalMembers(updateReqVO.getParticipantMemberIds().size());
        }

        classAssignmentMapper.updateById(updateDO);

        log.info("用户 {} 更新作业 {} 信息成功，参与成员数: {}",
                userId, assignmentId, updateReqVO.getParticipantMemberIds() != null ? updateReqVO.getParticipantMemberIds().size() : "未更新");
    }

    /**
     * 更新作业参与成员
     */
    private void updateAssignmentMembers(Long assignmentId, ClassAssignmentDO assignment, List<Long> participantMemberIds) {
        // 1. 获取当前作业的所有完成记录，按用户分组
        List<AssignmentCompletionDO> existingCompletions = assignmentCompletionMapper.selectByAssignmentId(assignmentId);
        Set<Long> existingMemberIds = existingCompletions.stream()
                .map(AssignmentCompletionDO::getUserId)
                .collect(Collectors.toSet());

        // 2. 验证成员是否都属于相关班级
        Set<Long> validMemberIds = new HashSet<>();

        if (assignment.getIsMultiClass() != null && assignment.getIsMultiClass()) {
            // 跨班级作业：验证成员是否属于任一关联班级
            List<Long> classIds = assignmentClassMapper.selectClassIdsByAssignmentId(assignmentId);
            for (Long classId : classIds) {
                List<ClassMemberDO> classMembers = classMemberMapper.selectByClassId(classId);
                validMemberIds.addAll(classMembers.stream()
                        .map(ClassMemberDO::getUserId)
                        .collect(Collectors.toSet()));
            }
        } else if (assignment.getClassId() != null) {
            // 单班级作业：验证成员是否属于该班级
            List<ClassMemberDO> classMembers = classMemberMapper.selectByClassId(assignment.getClassId());
            validMemberIds.addAll(classMembers.stream()
                    .map(ClassMemberDO::getUserId)
                    .collect(Collectors.toSet()));
        }

        List<Long> invalidMemberIds = participantMemberIds.stream()
                .filter(memberId -> !validMemberIds.contains(memberId))
                .collect(Collectors.toList());

        if (!invalidMemberIds.isEmpty()) {
            throw exception(CLASS_MEMBER_NOT_EXISTS, "成员ID不存在: " + invalidMemberIds);
        }

        // 3. 计算需要添加和移除的成员
        Set<Long> newMemberIds = new HashSet<>(participantMemberIds);
        Set<Long> membersToAdd = new HashSet<>(newMemberIds);
        membersToAdd.removeAll(existingMemberIds); // 需要新增的成员

        Set<Long> membersToRemove = new HashSet<>(existingMemberIds);
        membersToRemove.removeAll(newMemberIds); // 需要移除的成员

        // 4. 移除不再参与的成员的完成记录
        if (!membersToRemove.isEmpty()) {
            for (Long memberIdToRemove : membersToRemove) {
                assignmentCompletionMapper.delete(new LambdaQueryWrapperX<AssignmentCompletionDO>()
                        .eq(AssignmentCompletionDO::getAssignmentId, assignmentId)
                        .eq(AssignmentCompletionDO::getUserId, memberIdToRemove));
            }
            log.info("作业 {} 移除成员: {}", assignmentId, membersToRemove);
        }

        // 5. 获取作业的绘本列表
        List<AssignmentBookDO> assignmentBooks = assignmentBookMapper.selectByAssignmentId(assignmentId);

        // 6. 为新增的参与成员创建作业完成记录
        if (!membersToAdd.isEmpty()) {
            for (Long memberId : membersToAdd) {
                for (AssignmentBookDO assignmentBook : assignmentBooks) {
                    AssignmentCompletionDO completion = AssignmentCompletionDO.builder()
                            .assignmentId(assignmentId)
                            .userId(memberId)
                            .bookId(assignmentBook.getBookId())
                            .completionType(assignment.getRequirementType()) // 使用作业的要求类型
                            .isCompleted(false)
                            .score(0)
                            .build();
                    assignmentCompletionMapper.insert(completion);
                }
            }
            log.info("作业 {} 新增成员: {}", assignmentId, membersToAdd);
        }

        log.info("作业 {} 成员更新完成，当前参与成员: {} 人", assignmentId, participantMemberIds.size());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAssignment(Long assignmentId, Long userId) {
        // 检查作业是否存在
        ClassAssignmentDO assignment = validateAssignmentExists(assignmentId);

        // 检查用户是否为作业创建者
        if (!assignment.getCreatorId().equals(userId)) {
            throw exception(ASSIGNMENT_NO_PERMISSION);
        }

        // 软删除作业
        classAssignmentMapper.deleteById(assignmentId);

        // 删除作业绘本关联
        assignmentBookMapper.deleteByAssignmentId(assignmentId);

        // 删除作业完成记录
        List<AssignmentCompletionDO> completions = assignmentCompletionMapper.selectByAssignmentId(assignmentId);
        for (AssignmentCompletionDO completion : completions) {
            assignmentCompletionMapper.deleteById(completion.getId());
        }

        log.info("用户 {} 删除作业 {} 成功", userId, assignmentId);
    }

    @Override
    public List<AssignmentCompletionRespVO> getAssignmentCompletions(Long assignmentId, Long userId) {
        // 检查作业是否存在
        ClassAssignmentDO assignment = validateAssignmentExists(assignmentId);

        // 检查用户是否为作业创建者或班级成员
        boolean hasPermission = false;
        if (assignment.getCreatorId().equals(userId)) {
            // 用户是作业创建者，有权限查看
            hasPermission = true;
        } else if (assignment.getIsMultiClass() != null && assignment.getIsMultiClass()) {
            // 跨班级作业：检查用户是否为任一关联班级的成员
            List<Long> classIds = assignmentClassMapper.selectClassIdsByAssignmentId(assignmentId);
            for (Long classId : classIds) {
                if (classService.isClassMember(classId, userId)) {
                    hasPermission = true;
                    break;
                }
            }
        } else if (assignment.getClassId() != null) {
            // 单班级作业：检查用户是否为班级成员
            hasPermission = classService.isClassMember(assignment.getClassId(), userId);
        }

        if (!hasPermission) {
            throw exception(CLASS_MEMBER_NOT_EXISTS);
        }

        // 获取作业相关的学生成员（排除老师）
        List<ClassMemberDO> students = new ArrayList<>();

        if (assignment.getIsMultiClass() != null && assignment.getIsMultiClass()) {
            // 跨班级作业：获取所有相关班级的学生成员
            List<Long> classIds = assignmentClassMapper.selectClassIdsByAssignmentId(assignmentId);
            for (Long classId : classIds) {
                List<ClassMemberDO> classMembers = classMemberMapper.selectByClassId(classId);
                List<ClassMemberDO> classStudents = classMembers.stream()
                        .filter(member -> !"teacher".equals(member.getRole()))
                        .collect(Collectors.toList());
                students.addAll(classStudents);
            }
        } else if (assignment.getClassId() != null) {
            // 单班级作业：获取该班级的学生成员
            List<ClassMemberDO> members = classMemberMapper.selectByClassId(assignment.getClassId());
            students = members.stream()
                    .filter(member -> !"teacher".equals(member.getRole()))
                    .collect(Collectors.toList());
        }

        if (students.isEmpty()) {
            log.info("作业 {} 没有找到相关学生成员", assignmentId);
            return new ArrayList<>();
        }

        log.info("作业 {} 找到学生成员数量: {}", assignmentId, students.size());

        // 查询作业完成记录
        List<AssignmentCompletionDO> completions = assignmentCompletionMapper.selectByAssignmentId(assignmentId);
        log.info("作业 {} 完成记录数量: {}", assignmentId, completions.size());

        // 按用户分组统计完成情况
        Map<Long, List<AssignmentCompletionDO>> userCompletionMap = completions.stream()
                .collect(Collectors.groupingBy(AssignmentCompletionDO::getUserId));

        // 获取学生用户信息
        Set<Long> studentUserIds = students.stream().map(ClassMemberDO::getUserId).collect(Collectors.toSet());
        List<UserDO> users = userService.getUserList(studentUserIds);
        Map<Long, UserDO> userMap = users.stream()
                .collect(Collectors.toMap(UserDO::getId, u -> u));

        // 转换为响应VO - 只显示已完成作业的学生
        List<AssignmentCompletionRespVO> result = new ArrayList<>();
        for (ClassMemberDO student : students) {
            Long studentUserId = student.getUserId();
            UserDO user = userMap.get(studentUserId);
            if (user == null) continue;

            List<AssignmentCompletionDO> userCompletions = userCompletionMap.getOrDefault(studentUserId, new ArrayList<>());

            // 统计完成情况
            long completedCount = userCompletions.stream()
                    .filter(AssignmentCompletionDO::getIsCompleted)
                    .count();

            // 只显示已完成作业的学生
            log.debug("学生 {} ({}) 完成情况: {}/{} 本", user.getNickname(), user.getId(), completedCount, assignment.getTotalBooks());

            if (completedCount == assignment.getTotalBooks()) {
                log.info("学生 {} ({}) 已完成所有绘本，添加到已完成列表", user.getNickname(), user.getId());
                AssignmentCompletionRespVO respVO = new AssignmentCompletionRespVO();
                respVO.setUserId(user.getId());
                respVO.setNickname(user.getNickname());
                respVO.setAvatar(user.getAvatar());
                respVO.setCompletedBooks((int) completedCount);
                respVO.setTotalBooks(assignment.getTotalBooks());
                respVO.setStatus("已完成");

                // 获取最后完成时间
                userCompletions.stream()
                        .filter(AssignmentCompletionDO::getIsCompleted)
                        .map(AssignmentCompletionDO::getCompletedAt)
                        .max(LocalDateTime::compareTo)
                        .ifPresent(respVO::setCompletedAt);

                // 如果是配音作业，获取配音文件
                if ("audio".equals(assignment.getRequirementType())) {
                    userCompletions.stream()
                            .filter(c -> c.getRecordingUrl() != null)
                            .findFirst()
                            .ifPresent(c -> respVO.setRecordingUrl(c.getRecordingUrl()));
                }

                // 转换URL
                respVO.convertUrls();

                result.add(respVO);
            }
        }

        log.info("获取作业完成情况，作业ID: {}，总学生数: {}，已完成学生数: {}",
                assignmentId, students.size(), result.size());
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void completeAssignment(Long assignmentId, Long userId, AssignmentCompleteReqVO completeReqVO) {
        // 检查作业是否存在
        ClassAssignmentDO assignment = validateAssignmentExists(assignmentId);

        // 检查用户是否为班级成员（作业完成只能由学生执行，不允许老师代替完成）
        boolean hasPermission = false;
        if (assignment.getIsMultiClass() != null && assignment.getIsMultiClass()) {
            // 跨班级作业：检查用户是否为任一关联班级的成员
            List<Long> classIds = assignmentClassMapper.selectClassIdsByAssignmentId(assignmentId);
            for (Long classId : classIds) {
                if (classService.isClassMember(classId, userId)) {
                    hasPermission = true;
                    break;
                }
            }
        } else if (assignment.getClassId() != null) {
            // 单班级作业：检查用户是否为班级成员
            hasPermission = classService.isClassMember(assignment.getClassId(), userId);
        }

        if (!hasPermission) {
            throw exception(CLASS_MEMBER_NOT_EXISTS);
        }

        // 检查绘本是否属于该作业
        List<AssignmentBookDO> assignmentBooks = assignmentBookMapper.selectByAssignmentId(assignmentId);
        boolean bookExists = assignmentBooks.stream()
                .anyMatch(ab -> ab.getBookId().equals(completeReqVO.getBookId()));
        if (!bookExists) {
            throw exception(ASSIGNMENT_BOOK_NOT_EXISTS);
        }

        // 检查是否已有完成记录
        AssignmentCompletionDO existingCompletion = assignmentCompletionMapper
                .selectByAssignmentIdAndUserIdAndBookId(assignmentId, userId, completeReqVO.getBookId());

        if (existingCompletion != null) {
            // 更新现有记录 - 无论作业要求是什么，阅读完成即视为作业完成
            existingCompletion.setCompletionType(completeReqVO.getCompletionType());
            existingCompletion.setIsCompleted(true);
            existingCompletion.setCompletedAt(LocalDateTime.now());
            existingCompletion.setRecordingUrl(completeReqVO.getRecordingUrl());
            assignmentCompletionMapper.updateById(existingCompletion);
        } else {
            // 创建新的完成记录 - 无论作业要求是什么，阅读完成即视为作业完成
            AssignmentCompletionDO completion = AssignmentCompletionDO.builder()
                    .assignmentId(assignmentId)
                    .userId(userId)
                    .bookId(completeReqVO.getBookId())
                    .completionType(completeReqVO.getCompletionType())
                    .isCompleted(true)
                    .completedAt(LocalDateTime.now())
                    .recordingUrl(completeReqVO.getRecordingUrl())
                    .build();
            assignmentCompletionMapper.insert(completion);
        }

        // 更新作业完成人数统计
        Integer completedCount = assignmentCompletionMapper.countCompletedByAssignmentId(assignmentId);
        ClassAssignmentDO updateDO = ClassAssignmentDO.builder()
                .id(assignmentId)
                .completedCount(completedCount)
                .build();
        classAssignmentMapper.updateById(updateDO);

        log.info("用户 {} 完成作业 {} 的绘本 {} 成功，作业要求类型: {}，完成方式: 阅读完成",
                userId, assignmentId, completeReqVO.getBookId(), assignment.getRequirementType());
    }

    @Override
    public AssignmentStatsRespVO getAssignmentStats(Long assignmentId, Long userId) {
        // 检查作业是否存在
        ClassAssignmentDO assignment = validateAssignmentExists(assignmentId);

        // 检查用户是否为作业创建者或班级成员
        boolean hasPermission = false;
        if (assignment.getCreatorId().equals(userId)) {
            // 用户是作业创建者，有权限查看
            hasPermission = true;
        } else if (assignment.getIsMultiClass() != null && assignment.getIsMultiClass()) {
            // 跨班级作业：检查用户是否为任一关联班级的成员
            List<Long> classIds = assignmentClassMapper.selectClassIdsByAssignmentId(assignmentId);
            for (Long classId : classIds) {
                if (classService.isClassMember(classId, userId)) {
                    hasPermission = true;
                    break;
                }
            }
        } else if (assignment.getClassId() != null) {
            // 单班级作业：检查用户是否为班级成员
            hasPermission = classService.isClassMember(assignment.getClassId(), userId);
        }

        if (!hasPermission) {
            throw exception(CLASS_MEMBER_NOT_EXISTS);
        }

        // 构建统计信息
        AssignmentStatsRespVO respVO = new AssignmentStatsRespVO();
        respVO.setAssignmentId(assignmentId);
        respVO.setTotalMembers(assignment.getTotalMembers());
        respVO.setCompletedCount(assignment.getCompletedCount());
        respVO.setIncompleteCount(assignment.getTotalMembers() - assignment.getCompletedCount());

        // 计算完成率
        if (assignment.getTotalMembers() > 0) {
            double completionRate = (double) assignment.getCompletedCount() / assignment.getTotalMembers() * 100;
            respVO.setCompletionRate(Math.round(completionRate * 100.0) / 100.0);
        } else {
            respVO.setCompletionRate(0.0);
        }

        return respVO;
    }

    @Override
    public List<SelectableBookRespVO> getSelectableBooks(String language) {
        // 查询指定语言的绘本
        List<PictureBookDO> books = pictureBookMapper.selectByLanguage(language);
        if (books.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取绘本集信息
        Set<Long> bookSetIds = books.stream()
                .map(PictureBookDO::getBookSetId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        Map<Long, BookSetDO> bookSetMap = new HashMap<>();
        if (!bookSetIds.isEmpty()) {
            List<BookSetDO> bookSets = bookSetMapper.selectBatchIds(bookSetIds);
            bookSetMap = bookSets.stream()
                    .collect(Collectors.toMap(BookSetDO::getId, Function.identity()));
        }

        // 转换为响应VO
        List<SelectableBookRespVO> result = new ArrayList<>();
        for (PictureBookDO book : books) {
            SelectableBookRespVO respVO = new SelectableBookRespVO();
            respVO.setId(book.getId());
            respVO.setTitle(book.getTitle());
            respVO.setCover(book.getCover());
            respVO.setLanguage(language);
            respVO.setPages(book.getPages());

            // 设置绘本集信息
            if (book.getBookSetId() != null) {
                BookSetDO bookSet = bookSetMap.get(book.getBookSetId());
                if (bookSet != null) {
                    respVO.setBookSetId(bookSet.getId());
                    respVO.setBookSetTitle(bookSet.getTitle());
                    respVO.setBookSetCover(bookSet.getCover());
                }
            }

            // 转换URL
            respVO.convertUrls();

            result.add(respVO);
        }

        return result;
    }

    @Override
    public List<BookSetSelectableRespVO> getSelectableBookSets(String language) {
        // 查询指定语言的绘本集，使用自定义的selectList方法
        List<BookSetDO> bookSets = bookSetMapper.selectList(language, (String) null);
        if (bookSets.isEmpty()) {
            return new ArrayList<>();
        }

        // 转换为响应VO
        List<BookSetSelectableRespVO> result = new ArrayList<>();
        for (BookSetDO bookSet : bookSets) {
            BookSetSelectableRespVO respVO = new BookSetSelectableRespVO();
            respVO.setId(bookSet.getId());
            respVO.setTitle(bookSet.getTitle());
            respVO.setDescription(bookSet.getDescription());
            respVO.setCover(bookSet.getCover());
            respVO.setLanguage(language);
            respVO.setBookCount(bookSet.getBookCount());
            respVO.setDifficultyLevel(bookSet.getDifficultyLevel());
            respVO.setAgeRange(bookSet.getAgeRange());

            // 转换URL
            respVO.convertUrls();

            result.add(respVO);
        }

        return result;
    }

    @Override
    public List<SelectableBookRespVO> getBooksByBookSetId(Long bookSetId) {
        // 查询绘本集内的绘本
        List<PictureBookDO> books = pictureBookMapper.selectByBookSetId(bookSetId);
        if (books.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取绘本集信息
        BookSetDO bookSet = bookSetMapper.selectById(bookSetId);
        if (bookSet == null) {
            return new ArrayList<>();
        }

        // 转换为响应VO
        List<SelectableBookRespVO> result = new ArrayList<>();
        for (PictureBookDO book : books) {
            SelectableBookRespVO respVO = new SelectableBookRespVO();
            respVO.setId(book.getId());
            respVO.setTitle(book.getTitle());
            respVO.setCover(book.getCover());
            respVO.setLanguage(bookSet.getLanguage()); // 使用绘本集的语言信息
            respVO.setPages(book.getPages());

            // 设置绘本集信息
            respVO.setBookSetId(bookSet.getId());
            respVO.setBookSetTitle(bookSet.getTitle());
            respVO.setBookSetCover(bookSet.getCover());

            // 转换URL
            respVO.convertUrls();

            result.add(respVO);
        }

        return result;
    }

    @Override
    public ClassAssignmentDO getAssignment(Long assignmentId) {
        return classAssignmentMapper.selectById(assignmentId);
    }

    @Override
    public boolean hasAssignmentPermission(Long assignmentId, Long userId) {
        ClassAssignmentDO assignment = classAssignmentMapper.selectById(assignmentId);
        return assignment != null && assignment.getCreatorId().equals(userId);
    }

    @Override
    public boolean isAssignmentClassMember(Long assignmentId, Long userId) {
        ClassAssignmentDO assignment = classAssignmentMapper.selectById(assignmentId);
        if (assignment == null) {
            return false;
        }

        if (assignment.getIsMultiClass() != null && assignment.getIsMultiClass()) {
            // 跨班级作业：检查用户是否为任一关联班级的成员
            List<Long> classIds = assignmentClassMapper.selectClassIdsByAssignmentId(assignmentId);
            for (Long classId : classIds) {
                if (classService.isClassMember(classId, userId)) {
                    return true;
                }
            }
            return false;
        } else {
            // 单班级作业：检查用户是否为班级成员
            return classService.isClassMember(assignment.getClassId(), userId);
        }
    }

    // =============================================
    // 作业未完成情况管理实现
    // =============================================

    @Override
    public List<IncompleteStudentRespVO> getIncompleteStudents(Long assignmentId, Long userId) {
        // 检查作业是否存在
        ClassAssignmentDO assignment = validateAssignmentExists(assignmentId);

        // 检查用户是否为作业创建者或班级成员
        boolean hasPermission = false;
        if (assignment.getCreatorId().equals(userId)) {
            // 用户是作业创建者，有权限查看
            hasPermission = true;
        } else if (assignment.getIsMultiClass() != null && assignment.getIsMultiClass()) {
            // 跨班级作业：检查用户是否为任一关联班级的成员或创建者
            List<Long> classIds = assignmentClassMapper.selectClassIdsByAssignmentId(assignmentId);
            for (Long classId : classIds) {
                if (classService.isClassCreator(classId, userId) || classService.isClassMember(classId, userId)) {
                    hasPermission = true;
                    break;
                }
            }
        } else if (assignment.getClassId() != null) {
            // 单班级作业：检查用户是否为班级创建者或成员
            hasPermission = classService.isClassCreator(assignment.getClassId(), userId) ||
                    classService.isClassMember(assignment.getClassId(), userId);
        }

        if (!hasPermission) {
            throw exception(CLASS_NO_PERMISSION);
        }

        // 获取作业完成记录，基于实际参与成员而不是班级所有成员
        List<AssignmentCompletionDO> completions = assignmentCompletionMapper.selectByAssignmentId(assignmentId);
        if (completions.isEmpty()) {
            return new ArrayList<>();
        }

        // 从完成记录中获取实际参与作业的用户ID
        Set<Long> participantUserIds = completions.stream()
                .map(AssignmentCompletionDO::getUserId)
                .collect(Collectors.toSet());

        // 获取参与用户的信息
        List<UserDO> users = userService.getUserList(participantUserIds);
        Map<Long, UserDO> userMap = users.stream().collect(Collectors.toMap(UserDO::getId, u -> u));

        // 按用户分组完成记录
        Map<Long, List<AssignmentCompletionDO>> userCompletionMap = completions.stream()
                .collect(Collectors.groupingBy(AssignmentCompletionDO::getUserId));

        // 构建未完成学生列表
        List<IncompleteStudentRespVO> result = new ArrayList<>();
        for (Long participantUserId : participantUserIds) {
            UserDO user = userMap.get(participantUserId);
            if (user == null) continue;

            List<AssignmentCompletionDO> userCompletions = userCompletionMap.getOrDefault(participantUserId, new ArrayList<>());

            // 统计完成情况
            long completedCount = userCompletions.stream()
                    .filter(AssignmentCompletionDO::getIsCompleted)
                    .count();

            // 只返回未完全完成的学生
            if (completedCount < assignment.getTotalBooks()) {
                IncompleteStudentRespVO respVO = new IncompleteStudentRespVO();
                respVO.setUserId(user.getId());
                respVO.setNickname(user.getNickname());
                respVO.setAvatar(user.getAvatar());
                respVO.setCompletedBooks((int) completedCount);
                respVO.setTotalBooks(assignment.getTotalBooks());
                respVO.setRemainingBooks(assignment.getTotalBooks() - (int) completedCount);
                respVO.setIsStarted(completedCount > 0);

                // 获取最后提交时间
                userCompletions.stream()
                        .filter(AssignmentCompletionDO::getIsCompleted)
                        .map(AssignmentCompletionDO::getCompletedAt)
                        .max(LocalDateTime::compareTo)
                        .ifPresent(respVO::setLastSubmitTime);

                // 计算进度和状态
                respVO.calculateProgressPercentage();
                respVO.setCompletionStatus();

                // 转换URL
                respVO.convertUrls();

                result.add(respVO);
            }
        }

        log.info("获取作业未完成学生，作业ID: {}，参与学生数: {}，未完成学生数: {}",
                assignmentId, participantUserIds.size(), result.size());
        return result;
    }

    @Override
    public List<IncompleteAssignmentRespVO> getStudentIncompleteAssignments(Long classId, Long userId) {
        // 检查班级是否存在
        classService.getClass(classId);

        // 检查用户是否为班级创建者或成员
        if (!classService.isClassCreator(classId, userId) &&
                !classService.isClassMember(classId, userId)) {
            throw exception(CLASS_NO_PERMISSION);
        }

        // 查询班级作业
        List<ClassAssignmentDO> assignments = classAssignmentMapper.selectByClassId(classId);
        if (assignments.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取用户的作业完成记录
        List<IncompleteAssignmentRespVO> result = new ArrayList<>();
        for (ClassAssignmentDO assignment : assignments) {
            List<AssignmentCompletionDO> userCompletions = assignmentCompletionMapper
                    .selectByAssignmentIdAndUserId(assignment.getId(), userId);

            // 统计完成情况
            long completedCount = userCompletions.stream()
                    .filter(AssignmentCompletionDO::getIsCompleted)
                    .count();

            // 只返回未完全完成的作业
            if (completedCount < assignment.getTotalBooks()) {
                IncompleteAssignmentRespVO respVO = new IncompleteAssignmentRespVO();
                respVO.setAssignmentId(assignment.getId());
                respVO.setTitle(assignment.getTitle());
                respVO.setDescription(assignment.getDescription());
                // 将LocalDate转换为LocalDateTime（设置为当天23:59:59）
                respVO.setAssignmentDate(assignment.getAssignmentDate() != null ?
                        assignment.getAssignmentDate().atTime(23, 59, 59) : null);
                respVO.setRequirementType(assignment.getRequirementType());
                respVO.setTotalBooks(assignment.getTotalBooks());
                respVO.setCompletedBooks((int) completedCount);

                // 计算进度百分比
                double progressPercentage = assignment.getTotalBooks() > 0 ?
                        (double) completedCount / assignment.getTotalBooks() * 100 : 0.0;
                respVO.setProgressPercentage(Math.round(progressPercentage * 100.0) / 100.0);

                // 计算剩余天数和是否逾期
                LocalDate now = LocalDate.now();
                if (assignment.getAssignmentDate() != null) {
                    long daysBetween = ChronoUnit.DAYS.between(now, assignment.getAssignmentDate());
                    respVO.setRemainingDays((int) daysBetween);
                    respVO.setIsOverdue(daysBetween < 0);
                } else {
                    respVO.setRemainingDays(null);
                    respVO.setIsOverdue(false);
                }

                // 设置班级信息
                IncompleteAssignmentRespVO.ClassInfo classInfo = new IncompleteAssignmentRespVO.ClassInfo();
                classInfo.setClassId(classId);
                // 这里可以从classService获取班级名称
                classInfo.setClassName("班级" + classId); // 简化处理，实际应该查询班级名称
                respVO.setClassInfo(classInfo);

                // 获取未完成的绘本列表
                List<AssignmentBookDO> assignmentBooks = assignmentBookMapper.selectByAssignmentId(assignment.getId());
                Set<Long> completedBookIds = userCompletions.stream()
                        .filter(AssignmentCompletionDO::getIsCompleted)
                        .map(AssignmentCompletionDO::getBookId)
                        .collect(Collectors.toSet());

                List<IncompleteAssignmentRespVO.IncompleteBook> incompleteBooks = new ArrayList<>();
                for (AssignmentBookDO assignmentBook : assignmentBooks) {
                    if (!completedBookIds.contains(assignmentBook.getBookId())) {
                        // 获取绘本信息
                        PictureBookDO book = pictureBookMapper.selectById(assignmentBook.getBookId());
                        if (book != null) {
                            IncompleteAssignmentRespVO.IncompleteBook incompleteBook = new IncompleteAssignmentRespVO.IncompleteBook();
                            incompleteBook.setBookId(book.getId());
                            incompleteBook.setTitle(book.getTitle());
                            incompleteBook.setCover(book.getCover());

                            // 检查是否已开始（有未完成的记录）
                            boolean isStarted = userCompletions.stream()
                                    .anyMatch(c -> c.getBookId().equals(book.getId()));
                            incompleteBook.setIsStarted(isStarted);

                            incompleteBooks.add(incompleteBook);
                        }
                    }
                }
                respVO.setIncompleteBooks(incompleteBooks);

                result.add(respVO);
            }
        }

        return result;
    }

    @Override
    public ClassAssignmentSummaryRespVO getClassAssignmentSummary(Long classId, Long userId) {
        // 检查班级是否存在
        ClassDO classInfo = classService.getClass(classId);

        // 检查用户是否为班级创建者或成员
        if (!classService.isClassCreator(classId, userId) &&
                !classService.isClassMember(classId, userId)) {
            throw exception(CLASS_NO_PERMISSION);
        }

        // 获取班级成员数量
        Integer memberCount = classMemberMapper.countByClassId(classId);

        // 查询班级作业
        List<ClassAssignmentDO> assignments = classAssignmentMapper.selectByClassId(classId);

        ClassAssignmentSummaryRespVO respVO = new ClassAssignmentSummaryRespVO();
        respVO.setClassId(classId);
        respVO.setClassName(classInfo.getClassName());
        respVO.setTotalMembers(memberCount);
        respVO.setTotalAssignments(assignments.size());
        respVO.setLastUpdateTime(LocalDateTime.now());

        if (assignments.isEmpty()) {
            respVO.setCompletedAssignments(0);
            respVO.setInProgressAssignments(0);
            respVO.setNotStartedAssignments(0);
            respVO.setOverdueAssignments(0);
            respVO.setOverallCompletionRate(0.0);
            respVO.setAssignmentSummaries(new ArrayList<>());
            return respVO;
        }

        // 统计各种状态的作业数量
        int completedAssignments = 0;
        int inProgressAssignments = 0;
        int notStartedAssignments = 0;
        int overdueAssignments = 0;

        List<ClassAssignmentSummaryRespVO.AssignmentSummary> assignmentSummaries = new ArrayList<>();
        LocalDate now = LocalDate.now();

        for (ClassAssignmentDO assignment : assignments) {
            ClassAssignmentSummaryRespVO.AssignmentSummary summary = new ClassAssignmentSummaryRespVO.AssignmentSummary();
            summary.setAssignmentId(assignment.getId());
            summary.setTitle(assignment.getTitle());
            // 将LocalDate转换为LocalDateTime（设置为当天23:59:59）
            summary.setAssignmentDate(assignment.getAssignmentDate() != null ?
                    assignment.getAssignmentDate().atTime(23, 59, 59) : null);
            summary.setTotalBooks(assignment.getTotalBooks());
            summary.setCompletedCount(assignment.getCompletedCount());
            summary.setIncompleteCount(memberCount - assignment.getCompletedCount());

            // 计算完成率
            if (memberCount > 0) {
                double completionRate = (double) assignment.getCompletedCount() / memberCount * 100;
                summary.setCompletionRate(Math.round(completionRate * 100.0) / 100.0);
            } else {
                summary.setCompletionRate(0.0);
            }

            // 判断是否逾期
            boolean isOverdue = assignment.getAssignmentDate() != null &&
                    assignment.getAssignmentDate().isBefore(now);
            summary.setIsOverdue(isOverdue);
            if (isOverdue) {
                overdueAssignments++;
            }

            // 判断作业状态
            if (assignment.getCompletedCount().equals(memberCount)) {
                summary.setStatus("已完成");
                completedAssignments++;
            } else if (assignment.getCompletedCount() > 0) {
                summary.setStatus("进行中");
                inProgressAssignments++;
            } else {
                summary.setStatus("未开始");
                notStartedAssignments++;
            }

            assignmentSummaries.add(summary);
        }

        respVO.setCompletedAssignments(completedAssignments);
        respVO.setInProgressAssignments(inProgressAssignments);
        respVO.setNotStartedAssignments(notStartedAssignments);
        respVO.setOverdueAssignments(overdueAssignments);
        respVO.setAssignmentSummaries(assignmentSummaries);

        // 计算整体完成率
        respVO.calculateOverallCompletionRate();

        return respVO;
    }

    @Override
    public List<AssignmentRespVO> getOverdueAssignments(Long classId, Long userId) {
        // 检查班级是否存在
        classService.getClass(classId);

        // 检查用户是否为班级创建者或成员
        if (!classService.isClassCreator(classId, userId) &&
                !classService.isClassMember(classId, userId)) {
            throw exception(CLASS_NO_PERMISSION);
        }

        // 查询班级作业
        List<ClassAssignmentDO> assignments = classAssignmentMapper.selectByClassId(classId);
        if (assignments.isEmpty()) {
            return new ArrayList<>();
        }

        // 筛选逾期作业
        LocalDate now = LocalDate.now();
        List<AssignmentRespVO> result = new ArrayList<>();

        for (ClassAssignmentDO assignment : assignments) {
            // 检查是否逾期
            if (assignment.getAssignmentDate() != null && assignment.getAssignmentDate().isBefore(now)) {
                AssignmentRespVO respVO = BeanUtils.toBean(assignment, AssignmentRespVO.class);

                // 获取作业绘本列表
                List<AssignmentBookDO> assignmentBooks = assignmentBookMapper.selectByAssignmentId(assignment.getId());
                Set<Long> bookIds = assignmentBooks.stream()
                        .map(AssignmentBookDO::getBookId)
                        .collect(Collectors.toSet());

                if (!bookIds.isEmpty()) {
                    List<PictureBookDO> books = pictureBookMapper.selectBatchIds(bookIds);
                    List<AssignmentRespVO.AssignmentBookRespVO> bookInfos = books.stream()
                            .map(book -> {
                                AssignmentRespVO.AssignmentBookRespVO bookInfo = new AssignmentRespVO.AssignmentBookRespVO();
                                bookInfo.setId(book.getId());
                                bookInfo.setTitle(book.getTitle());
                                bookInfo.setCover(book.getCover());
                                return bookInfo;
                            })
                            .collect(Collectors.toList());
                    respVO.setBooks(bookInfos);
                }

                // 转换URL
                respVO.convertUrls();

                result.add(respVO);
            }
        }

        return result;
    }

    @Override
    public List<AssignmentClassRespVO> getAssignmentClasses(Long assignmentId, Long userId) {
        // 检查作业是否存在
        ClassAssignmentDO assignment = validateAssignmentExists(assignmentId);

        // 检查用户是否有权限查看作业
        if (!isAssignmentClassMember(assignmentId, userId) && !assignment.getCreatorId().equals(userId)) {
            throw exception(ASSIGNMENT_NO_PERMISSION);
        }

        List<AssignmentClassRespVO> result = new ArrayList<>();

        if (assignment.getIsMultiClass() != null && assignment.getIsMultiClass()) {
            // 跨班级作业：获取关联的班级列表
            List<Long> classIds = assignmentClassMapper.selectClassIdsByAssignmentId(assignmentId);
            for (Long classId : classIds) {
                ClassDO classDO = classService.getClass(classId);
                if (classDO != null) {
                    AssignmentClassRespVO respVO = new AssignmentClassRespVO();
                    respVO.setClassId(classId);
                    respVO.setClassName(classDO.getClassName());
                    result.add(respVO);
                }
            }
        } else if (assignment.getClassId() != null) {
            // 单班级作业：返回单个班级
            ClassDO classDO = classService.getClass(assignment.getClassId());
            if (classDO != null) {
                AssignmentClassRespVO respVO = new AssignmentClassRespVO();
                respVO.setClassId(assignment.getClassId());
                respVO.setClassName(classDO.getClassName());
                result.add(respVO);
            }
        }

        return result;
    }
}
